package com.dommettj.rawfix.message;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MessageUtils {

    public static MessageType getMessageType(final String message) throws UnknownMessageTypeException {
        return getMessageType(message, '\u0001');
    }

    public static MessageType getMessageType(final String message, final char tagDelimiter) throws UnknownMessageTypeException {

        final Pattern typePattern = Pattern.compile(".*35=(.*?)" + getEscapedDelimiter(tagDelimiter) + ".*");
        final Matcher typeMatcher = typePattern.matcher(message);
        typeMatcher.matches();

        try {
            return MessageType.fromTypeString(typeMatcher.group(1));
        } catch(IllegalStateException e) {
            throw new UnknownMessageTypeException(message);
        }
    }

    public static List<String> getMessages(final String content) {

        final List<String> messages = new ArrayList<String>();
        buildMessageList(content, messages);
        return messages;
    }

    public static char getTagDelimiter(final String message) throws MalformedMessageException {

        final Pattern delimiterPattern = Pattern.compile("^8=(.*?)(.)9=.*");
        final Matcher delimiterMatcher = delimiterPattern.matcher(message);

        if(delimiterMatcher.matches()) {
            return delimiterMatcher.group(2).charAt(0);
        }
        throw new MalformedMessageException(message);
    }

    public static String getEscapedDelimiter(final char delimiter) {

        if(delimiter == '|') {
            return "\\|";
        } else {
            return String.valueOf(delimiter);
        }
    }

    private static void buildMessageList(final String content, final List<String> messages) {

        final Pattern messageMatch = Pattern.compile(".*?(8=FIX.*?10=...\u0001)(.*)");
        final Matcher messageMatcher = messageMatch.matcher(content);

        if(messageMatcher.matches()) {
            messages.add(messageMatcher.group(1));
            buildMessageList(messageMatcher.group(2), messages);
        }
    }
}
